#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/3/17 11:12
# @Author  : Wang Yuhang
# @File    : forms.py
# @Func    :

from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import Length, Email, DataRequired, Regexp, EqualTo
from ..models import User
from wtforms import ValidationError

import email_validator


class LoginForm(FlaskForm):
    email = StringField('邮箱', validators=(DataRequired(), Length(1, 64), Email()))
    password = PasswordField('密码', validators=[DataRequired()])
    remember_me = BooleanField('记住我')
    submit = SubmitField('登录')


class RegistrationForm(FlaskForm):
    email = StringField('邮箱', validators=[DataRequired(), Length(1, 64), Email()])
    username = StringField('用户名', validators=[DataRequired(), Length(1, 64), Regexp('^[A-Za-z][A-Za-z0-9_,]*$', 0,
                                                '用户名只能包含字母、数字、下划线和点号')])
    password = PasswordField('输入密码', validators=[DataRequired(), EqualTo('password2', message='两次密码输入不一致')])
    password2 = PasswordField('确认密码', validators=[DataRequired()])
    submit = SubmitField('注册')

    def validate_email(self, field):
        if User.query.filter_by(email=field.data).first():
            raise ValidationError('邮箱已被注册')

    def validate_username(self, field):
        if User.query.filter_by(username=field.data).first():
            raise ValidationError('用户名已被注册')




